package com.lfy.fyadmin.util;

import cn.dev33.satoken.stp.StpUtil;
import com.lfy.fyadmin.entity.User;
import com.lfy.fyadmin.entity.UserRole;
import com.lfy.fyadmin.entity.Role;
import com.lfy.fyadmin.service.UserService;
import com.lfy.fyadmin.service.UserRoleService;
import com.lfy.fyadmin.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 权限检查工具类
 */
@Component
public class PermissionCheckUtil {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    /**
     * 检查当前用户是否为管理员
     * @return 是否为管理员
     */
    public boolean isCurrentUserAdmin() {
        try {
            // 获取当前登录用户ID
            Long currentUserId = Long.valueOf(StpUtil.getLoginId().toString());
            
            // 查询用户角色
            List<UserRole> userRoles = userRoleService.lambdaQuery()
                    .eq(UserRole::getUserId, currentUserId)
                    .list();

            // 检查是否有管理员角色
            for (UserRole userRole : userRoles) {
                Role role = roleService.getById(userRole.getRoleId());
                if (role != null && "admin".equalsIgnoreCase(role.getCode())) {
                    return true;
                }
            }
            
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 检查当前用户是否有指定权限
     * @param permissionCode 权限编码
     * @return 是否有权限
     */
    public boolean hasPermission(String permissionCode) {
        // TODO: 实现具体的权限检查逻辑
        // 这里可以根据实际的权限模型来实现
        return isCurrentUserAdmin();
    }

    /**
     * 获取当前登录用户ID
     * @return 用户ID
     */
    public Long getCurrentUserId() {
        try {
            return Long.valueOf(StpUtil.getLoginId().toString());
        } catch (Exception e) {
            throw new IllegalArgumentException("用户未登录或登录已过期");
        }
    }

    /**
     * 检查当前用户是否已登录
     * @return 是否已登录
     */
    public boolean isCurrentUserLogin() {
        return StpUtil.isLogin();
    }
}